<template>
  <div>
          <el-header style="box-shadow: rgba(0, 0, 0, 0.05) 0 2px 20px 0.5px;border-radius:6px;padding:20px;height:56px">
          <div class="flexBox" >
              <el-breadcrumb separator="/">
                  <el-breadcrumb-item :to="{ path: '/home' }"
                  >首页</el-breadcrumb-item>
                  <el-breadcrumb-item>人事调动</el-breadcrumb-item>
                  <el-breadcrumb-item>转科管理</el-breadcrumb-item>
                  <el-breadcrumb-item>{{from}}</el-breadcrumb-item>
              </el-breadcrumb>
          </div>
        </el-header >
        <el-main style="box-shadow: rgba(0, 0, 0, 0.05) 0 2px 20px 0.5px;border-radius:6px;padding:20px;margin-top:20px">
          <el-row :gutter="0" v-if="this.from=='追加计划'" type="flex" justify="space-between">
            <label class="el-form-item__label"><i class="el-icon-user-solid" style="color: #3a8ee6"></i>{{ tableData[0].name }}</label>
            <label class="el-form-item__label">科室：<el-tag type="info">{{ tableData[0].dept }}</el-tag></label>
            <label class="el-form-item__label">片区：<el-tag type="warning">{{ tableData[0].dept }}</el-tag></label>
          </el-row>
          <el-divider v-if="this.from=='追加计划'"></el-divider>
            <div style="float:right">
               <el-button type="primary" style="margin-bottom:10px" @click="save" size="mini">保存</el-button>
               <el-button style="margin-bottom:10px;" @click="cancel" size="mini">返回</el-button>
            </div>
            <div style="clear:both"></div>
            <el-divider></el-divider>
          <el-table
            v-loading="showTable"
            :data="tableData"
            border
            style="width: 100%;margin-top:20px"
            :header-cell-style="{ background: 'rgb(245,247,250)' }"
          >
            <el-table-column
              fixed="left"
              type="selection"
              align="center">
            </el-table-column>
            <el-table-column
              label="姓名"
              prop="name"
              align="center"
              width="200">
            </el-table-column>
<!--            <el-table-column-->
<!--              label=""-->
<!--              prop=""-->
<!--              align="center"-->
<!--              v-if="showData.length==0"-->
<!--              >-->
<!--            </el-table-column>-->
            <el-table-column
              label="时间"
              align="center"
              >
                <template slot-scope="scope">
                  <el-date-picker
                    v-if="from=='新增计划'"
                    v-model="tableData[scope.$index].start_date"
                    type="date"
                    value-format="yyyy-MM-dd"
                    :value="tableData[scope.$index].start_date"
                    placeholder="选择日期:"
                    :picker-options="startDatePicker"
                    @change="selectStart($event,scope.$index)">
                  </el-date-picker>
                  <span v-else>{{tableData[scope.$index].start_date}}</span>
                  ~
                  <el-date-picker
                    v-if="from=='新增计划'"
                    v-model="tableData[scope.$index].end_date"
                    type="date"
                    :value="tableData[scope.$index].end_date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期:"
                    :picker-options="endDatePicker"
                    @change="selectEnd($event,scope.$index)">
                  </el-date-picker>
                  <span v-else>{{tableData[scope.$index].end_date}}</span>
                </template>
            </el-table-column>
            <el-table-column
              label="科室"
              prop="dept"
              align="center"
              width="200">
              <template slot-scope="scope">
                <!-- @change传递多参数时，用$event接收默认值，后面再跟上需要的参数 -->
                <el-select v-if="from=='新增计划'" @change="getDept($event,scope.$index)" :value="tableData[scope.$index].dept">
                  <el-option v-for="i in deptOption" :label="i[0]" :value="i[0]"></el-option>
                </el-select>
                <span v-else>{{tableData[scope.$index].dept}}</span>
              </template>
            </el-table-column>

            <el-table-column
              align="center"
              fixed="right"
              width="80">
              <template slot-scope="scope">
                <i  class="el-icon-circle-close" style="cursor: pointer;color: #3a8ee6" @click="handleDelete(scope,scope.$index)"></i>
              </template>
              <template slot="header">
                <el-button v-if="from=='追加计划'" type="text" @click="newTurnPlan" size="mini"><i class="el-icon-circle-plus-outline"></i></el-button>
              </template>
            </el-table-column>

          </el-table>
          <div class="addButton" @click="addUser" v-if="from=='新增计划'">
            <i class="el-icon-circle-plus-outline"></i>添加
          </div>
          <el-dialog :visible.sync="showConfig" :append-to-body="true" :title="from" width="30%">
            <el-form :model="form" label-position="right" label-width="80px">
              <el-form-item label="开始时间:" :label-width="formLabelWidth">
                <el-date-picker
                  v-model="form.start_date"
                  type="date"
                  :picker-options="startDatePicker"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期:"
                  @change="selectStartAdd(form.start_date)">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="结束时间:" :label-width="formLabelWidth">
                <el-date-picker
                  v-model="form.end_date"
                  type="date"
                  :picker-options="endDatePicker"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期:">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="科室" :label-width="formLabelWidth">
                <el-select v-model="form.dept" placeholder="请选择">
                  <el-option
                    v-for="item in deptList"
                    :key="item['科室']"
                    :label="item['科室']"
                    :value="item['科室']">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <div slot="footer">
              <el-button size="mini" @click="showConfig = false">取 消</el-button>
              <el-button  size="mini" type="primary" @click="submitConfig">确 定</el-button>
            </div>
          </el-dialog>
          <el-dialog :visible.sync="showAdd" :append-to-body="true" title="添加人员" width="60%">
            <div>
              <el-input style="width: 100%;" size="small" v-model="filterText">
                <el-button size="mini" slot="append" icon="el-icon-search"></el-button>
              </el-input>
            </div>
            <div style="display: flex;flex-direction: column;justify-content: space-around;height: 500px;margin-top: 20px">
              <div style="border: #DCDFE6 1px solid;border-radius: 2px;margin-right: 20px;overflow-y: auto">
                <el-tree
                  ref="space"
                  :data="data"
                  :props="defaultProps"
                  @node-click="handleNodeClick"
                  :load="loadNode"
                  style="padding:20px"
                  show-checkbox
                  @check-change="handleCheckChange"
                  :filter-node-method="filterNode"></el-tree>
              </div>
              <div style="margin-top: 10px;display: flex;justify-content: end">
                <el-button type="primary" size="mini" @click="addUserChecked">确定</el-button>
                <el-button size="mini" @click="showAdd=false">取消</el-button>
              </div>
<!--              <div style="width: 20vw;display: flex;justify-content: center; align-items: center">-->
<!--&lt;!&ndash;                <el-button type="primary"><i class="el-icon-back"></i></el-button>&ndash;&gt;-->
<!--                <el-button type="primary" @click="handleChecked"><i class="el-icon-right"></i></el-button>-->
<!--              </div>-->
<!--              <div style="width: 50vw;border: #DCDFE6 1px solid;border-radius: 2px">-->
<!--                <el-tag v-for="item in showData">{{item.label}}</el-tag>-->
<!--              </div>-->
            </div>
          </el-dialog>
        </el-main>
  </div>
</template>

<script>
import TaskManager from "../service/TaskManager";

export default {
  name: 'newTurn',
  data() {
    return {
      startDatePicker:this.startDate(),
      endDatePicker:this.endDate(),
      startTemp:"",
      index: "",
      checkData: [],
      showData: [],
      filterText: "",
      formLabelWidth: "120px",
      form: {
        start_date: "",
        end_date: "",
        dept: "",
        name: "",
        duties: "",
        level: ""
      },
      defaultProps: {
        children: 'children',
        label: 'label',
        isLeaf: true
      },
      data: [],
      showTable: false,
      showAdd: false,
      showConfig: false,
      row: "",
      from: "",
      tableData: [],
      duties: [],
      deptList: [],
      levelList: [],
      deptOption: [],
    }
  },
  watch: {
    filterText(val) {
      this.$refs.space.filter(val)
    }
  },
  methods: {
    startDate(){
      return {
        disabledDate(time){
          return time.getTime() < Date.now() - 8.64e7
        }
      }
    },
    endDate(){
      let that=this
      return{
        disabledDate(time){
          return time.getTime() < new Date(that.startTemp)- 8.64e7
        }
      }
    },
    unEmpty(arr) {
      for (let key in arr) {
        if (arr[key][0] == '') {
          arr.splice(key, 1);
        }
      }
    },
    getDeptList() {
      let params = {
        name: '科室',
        ryxz: 0,
      }
      TaskManager.getOption(params)
        .then((res) => {
          console.log(res.data);
          this.unEmpty(res.data);
          this.deptOption = res.data;
          this.deptList = res.data;
        })
    },
    getDept(val, index) {
      if (val) {
        // console.log(this.showData)
        // this.$set(this.showData[0],"dept",val)
        this.tableData[index].dept = val;
      }
    },
    selectStart(val, index) {
      this.tableData[index].start_date = val;
      this.startTemp=val
    },
    selectStartAdd(val) {
      console.log(val)
      // this.tableData[index].start_date = val;
      this.startTemp=val
    },
    selectEnd(val, index) {
      this.tableData[index].end_date = val;
    },
    getTime(){
      let date=new Date().toLocaleString().split(' ')[0];
      let time=new Date().toLocaleString().split(' ')[1];
      let Now=date+" "+time;
      return Now;
    },
    //TODO 保存计划信息
    save() {
      console.log(this.tableData);
      for (let key in this.tableData) {
        let data = this.tableData[key];
        let params = {
          name: data.name,
          id: data.id,
          dept: data.dept,
          from: data.from,
          level: data.level,
          start_date: data.start_date,
          end_date: data.end_date,
          duties: data.duties,
          tempId:data.tempId
        }
        TaskManager.InsertTurnList(params).then(res => {
          if (res.data == 'success') {
            let paramss={
              name:"转科通知",
              message:`您有新的调科通知：【${window.localStorage.dept}-${window.localStorage.name}】将您派往【${data.dept}】进行轮转学习，时间为【${data.start_date}--${data.end_date}】`,
              date:this.getTime(),
              id:data.id
            }
            TaskManager.setMessage(paramss).then(()=>{
              this.$message({
                type: "success",
                message: "保存成功！"
              })
            });
          }
        })
      }
    },
    cancel() {
      this.$router.go(-1);
    },
    loadList(id) {
      console.log(id)
      this.showTable = true;
      if(id){
        console.log(333)
        TaskManager.getTurnList({id: id}).then((res) => {
          this.tableData = res.data;
          this.showTable = false;
          console.log(this.tableData)
        })
      }else{
        this.showTable = false;
        console.log(this.tableData)
        this.tableData=[]
      }
    },
    newTurnPlan() {
      this.showConfig = true;
    },
    addUser() {
      this.showAdd = true;
      this.loadTree();
    },
    addUserChecked() {
      this.showAdd = false;
      this.checkData.forEach(e=>{
        console.log(e);
        this.tableData.push(e);
      })
      // this.tableData.push(this.checkData);
      this.data = [];
    },
    //TODO 动态添加时间
    submitConfig() {
      let item = {
        name:this.tableData[0].name,
        start_date: this.form.start_date,
        end_date: this.form.end_date,
        dept:this.form.dept,
        from: this.tableData[0].from,
        id: this.tableData[0].id,
        level: this.tableData[0].level,
        duties: this.tableData[0].duties,
        tempId: "000"
      };
      this.tableData.push(item);
      this.showConfig = false;
    },
    loadNode(node) {
      if (node.level === 0) {
        return resolve([]);
      }
      if (node.level > 1) return resolve([]);
      setTimeout(() => {
        this.loadTreeData(res)
      }, 500);
    },
    handleDelete(index) {
      this.tableData.splice(index, 1);
    },
    handleNodeClick(res) {
      console.log(res)
      if (res.children == undefined) {
        this.showData = true;
        this.loadData(res.label)
      } else {
        this.loadTreeData(res)
      }
    },
    //TODO 获取选择信息
    handleCheckChange(data, checked, indeterminate) {
      console.log(data, checked, indeterminate);
      if (!data.children && checked == true) {
        let item = {
          name: data.label,
          id: data.id,
          from: data.from,
          level: data.level,
          duties: data.duties,
          dept: "",
          start_date: "",
          end_date: "",
          tempId:"000"
        }
        this.checkData.push(item);
      }else if(!data.children && checked == false){
        let index="";
        for(let key in this.checkData){
          if(this.checkData[key].id==data.id){
            index=key;
          }
        }
        this.checkData.splice(index,1);
      }
    },
    loadTree() {
      let params = {name: ''}
      TaskManager.getDeptTreeList(params)
        .then((res) => {
          for (let key in res.data) {
            if (res.data[key].科室 != '') {
              let item = {};
              item.id = key;
              item.label = res.data[key].科室;
              item.children = [];
              this.data.push(item);
            }
          }
          console.log(this.data)
          this.showList = false;
        })
    },
    loadTreeData(node) {
      console.log(node)
      if (node.children.length == '0') {
        let params = {name: node.label}
        TaskManager.getDeptTreeList(params)
          .then((res) => {
            for (let _key in res.data) {
              let item = {};
              item.label = res.data[_key].姓名;
              item.id = res.data[_key].工号;
              item.level = res.data[_key].人员层级;
              item.from = res.data[_key].科室;
              item.duties = res.data[_key].管理职务;
              this.data[node.id].children.push(item);
            }
          })
      }
    },
    filterNode(value, data) {
      if (!value) {
        return true
      }
      return data.label.indexOf(value) !== -1;
    },
  },
  mounted() {
    this.row=this.$route.params.row;
    this.from=this.$route.params.from;
    this.getDeptList();
    console.log(this.deptList)
    console.log(this.from)
    // this.form.name = this.row.name;
    if (this.from == '追加计划') {
      console.log(this.row)
      this.loadList(this.row.id);
    } else {
      console.log(222)
      this.loadList();
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.el-input.is-disabled .el-input__inner{
  width: 220px;
}

.addButton{
  border: #3a8ee6 1px dashed;
  margin-top: 10px;
  padding: 10px;
  color: #3a8ee6;
  cursor:pointer;
}
</style>
